<template>
    <div class="box">
        <el-form ref="formRef" :model="form" label-width="120px" status-icon :rules="rules" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="form.password" />
            </el-form-item>
            <el-form-item>
                <el-button class="btn" type="primary" @click="login(formRef)">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { userLogin } from '@/request/api'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
const store = useStore()
const router = useRouter()
const formRef = ref<FormInstance>()
const form = reactive({
    username: '',
    password: ''
})
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' },
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' },
    {
        min: 3,
        max: 10,
        message: "长度在 3 到 10 个字符",
        trigger: "blur",
    },]
})
const login = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(form)
            userLogin(form).then(res => {
                console.log(res, '管理员登录');
                if (res.code == 200) {
                    ElMessage({
                        type: 'success',
                        message: res.msg
                    })
                    // sessionStorage.setItem('userinfo', JSON.stringify(res.list))
                    store.dispatch('UserActions', res.list)
                    router.push('/home')
                } else {
                    ElMessage({
                        type: 'error',
                        message: res.msg
                    })
                }
            })

        } else {
            console.log('验证失败', fields)
        }
    })
}
</script>

<style scoped>
.box {
    width: 100wh;
    height: 100vh;
    text-align: center;
    background: #CCFFCC;
}

.box .demo-ruleForm {
    position: absolute;
    width: 400px;
    height: 300px;
    top: 300px;
    left: 700px;
}

.box .demo-ruleForm .btn {
    margin-left: 105px;
}
</style>
